import shutil
import os
import requests
import time
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from tqdm import trange
from img2pdf import conpdf

def download(url):
    # 浏览器启动参数设置
    options = webdriver.EdgeOptions()
    # 设置user-agent
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0'
    options.add_argument(f'user-agent={user_agent}')
    # 禁用浏览器中的自动化检测
    options.add_experimental_option("excludeSwitches", ['enable-automation', 'enable-logging'])
    options.add_experimental_option('useAutomationExtension', False)
    options.add_argument('--disable-blink-features=AutomationControlled')
    # 禁止显示保存密码提示框
    prefs = {"credentials_enable_service": False, "profile.password_manager_enabled": False}
    options.add_experimental_option("prefs", prefs)
    # 不关闭网页
    options.add_experimental_option("detach", True)
    # 仿真模拟手机操作
    # 指定设备名称即可
    options.add_experimental_option('mobileEmulation', {'deviceName': 'iPhone X'})
    # 最大化运行（全屏窗口）,不设置，取元素会报错
    options.add_argument('--start-maximized')
    driver = webdriver.Edge(options =options,service=EdgeService(EdgeChromiumDriverManager().install()))# => 打开浏览器时加入配置
    # 避免被浏览器检测出来使用了Selenium
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
        Object.defineProperty(navigator, 'webdriver', {
        get: () => undefined
        })
    """
    })
    driver.get(url)
    # 观察一下
    time.sleep(5)
    # 显示源码
    text = driver.page_source
    # 获取必要的参数        
    pos = text.index('secretId')
    sid = text[pos + 10:].split('"')[0]
    # sid:-4uPfTSYfE7SVWptfOmf2OG6QAMtOvcXNqhANCFed0FpkfXnm2OqvaBLCHcgUvT*
    pos = text.index('pageCount:')
    pages = int(text[pos + 10: pos + 15].split(',')[0])
    # pages:49
    id = url.split('.')[-2].split('-')[-1]
    # id:2358821619
    title = driver.title
    # title:【Renesas】CAN入门书 - 豆丁网
    # 去掉特殊字符/\:*?"<>|
    sets = ['/', '\\', ':', '*', '?', '"', '<', '>', '|']
    for char in title:
        if char in sets:
            title = title.replace(char, '')
    print(f'豆丁：《{title}》')
    print(id,sid)
    # 检查文件和文件夹
    if os.path.exists(f'./temp/{title}'):# 查看给定的文件/目录是否存在
        shutil.rmtree(f'./temp/{title}')# 存在，递归删除文件夹下的所有子文件夹和子文件
    os.makedirs(f'./temp/{title}')# 不存在，递归创建目录    
    if not os.path.exists(f'output'):# 查看给定的文件/目录是否存在
        os.makedirs(f'output')# 不存在，递归创建目录        
    if os.path.exists(f'./output/{title}.pdf'):# 查看给定的文件/目录是否存在
        os.remove(f'./output/{title}.pdf')# 删除指定路径的文件
    # 下载图片文件
    for i in trange(pages):
        time.sleep(1)
        url = f"https://docimg1.docin.com/docinpic.jsp?file={id}&width=1600&pageno={i + 1}&sid={sid}"
        res = requests.get(url)
        with open(f'./temp/{title}/{i+1}.jpg', 'wb') as f:
            f.write(res.content)
    # 关闭浏览器    
    driver.quit()
    # JPG转PDF
    print('下载完毕，正在转码')
    conpdf(f'output/{title}.pdf', f'./temp/{title}', '.jpg')